package com.fenghuo.map;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.fenghuo.model.Histroy;
import com.fenghuo.model.MapPoint;
import com.fenghuo.utils.CustomToast;
import com.fenghuo.utils.TimeUtil;
import com.fenghuo.utils.Utils;
import com.fenghuo.utils.Values;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.FinalDb;
import net.tsz.afinal.annotation.view.ViewInject;

import java.io.File;
import java.util.List;

public class Ac_Note extends FinalActivity {

    @ViewInject(id = R.id.tv_back_note, click = "onClick")
    TextView tv_back;
    @ViewInject(id = R.id.tv_note_place)
    TextView tv_place;
    @ViewInject(id = R.id.iv_ok_note, click = "onClick")
    ImageView iv_ok;
    @ViewInject(id = R.id.iv_fresh, click = "onClick")
    ImageView iv_refresh;
    @ViewInject(id = R.id.et_content_note, click = "onClick")
    EditText et_content;
    @ViewInject(id = R.id.linea_note_img)
    LinearLayout container;
    @ViewInject(id = R.id.iv_addimg, click = "onClick")
    ImageView iv_add;

    private Histroy histroy;//当前 闪记
    private String photopath;//图片路径
    private String photoname;//文件名
    private LocationClient locationClient;
    private String addstr = "";//百度定位提供的地址

    private FinalDb db = null;
    private List<MapPoint> list = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_note);

        histroy = new Histroy();
        locationClient = new LocationClient(Ac_Note.this);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");//返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(8000);//设置发起定位请求的间隔时间为8000ms
        option.setIsNeedAddress(true);//返回的定位结果包含地址信息
        option.setNeedDeviceDirect(false);//返回的定位结果包含手机机头的方向
        option.setOpenGps(true);
        locationClient.setLocOption(option);
        locationClient.registerLocationListener(listener);
        locationClient.start();
        db = FinalDb.create(Ac_Note.this, Values.DB_NAME);
        list = db.findAll(MapPoint.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Values.currenturl != null && !Values.currenturl.equals("")) {
            ImageView view = new ImageView(this);
            LayoutParams params = new LayoutParams(Utils.getpx(Ac_Note.this, 60), Utils.getpx(Ac_Note.this, 55));
            view.setClickable(true);
            String path = Environment.getExternalStorageDirectory() + Values.photo_Path + "/" + Values.currenturl;
            view.setBackgroundDrawable(Drawable.createFromPath(path));
            view.setLayoutParams(params);
            params.setMargins(2, 2, 2, 2);
            container.addView(view, 0);
            Values.allurls += Values.currenturl + ",";
            Values.currenturl = "";
        }
    }

    private void getlocation() {
        locationClient.start();
    }

    private void computLocation(double latitude, double longtitude, float radus) {
        double xpersent1 = (longtitude - Ac_Main.lefttopLot) / Ac_Main.dx;
        double ypersent1 = 1 - (latitude - Ac_Main.rightboLat) / Ac_Main.dy;
        int x = (int) (Values.mapW * xpersent1) + 30;
        int y = (int) (Values.mapH * ypersent1) + 130;
        Values.locationx = x;
        Values.locationy = y;
//		DbModel com.fenghuo.model = db.findDbModelBySQL("select name,min(abs(x-"+x+")+abs(y-"+y+")) as dd from MapPoint");
//		String place = com.fenghuo.model.getString("name");
//		System.out.println(com.fenghuo.model.toString()+"================finaldb");
//		tv_place.setText(place);
        int closey = 500;
        String place = "";
        for (MapPoint p : list) {
            int d = Math.abs(p.getX() - x) + Math.abs(p.getY() - y);
            if (d < closey) {
                closey = d;
                place = p.getName();
            }
        }
        tv_place.setText(place);
        if (place.equals(""))
            tv_place.setText(addstr);
        locationClient.stop();
    }

    private BDLocationListener listener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null)
                return;
            switch (location.getLocType()) {
                case 61://gps定位结果
                case 161://表示网络/wifi定位结果
                    computLocation(location.getLatitude(), location.getLongitude(), location.getRadius());
                    addstr = location.getAddrStr();
                    break;
                case 62://扫描整合定位依据失败。此时定位结果无效。
                case 63://网络异常，没有成功向服务器发起请求。此时定位结果无效。
                    new CustomToast(Ac_Note.this).ShowMsg("定位失败！请检查网络", CustomToast.Img_Info);
                    tv_place.setText("未知地点");
                    break;
                default:
                    break;
            }
        }
    };

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_back_note:
                if (!et_content.getText().toString().equals("")) {
                    new AlertDialog.Builder(Ac_Note.this).setTitle("确定放弃编辑？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface arg0, int arg1) {
                                    Values.currenturl = "";
                                    finish();
                                }
                            })
                            .setNegativeButton("取消", null)
                            .show();
                } else {
                    finish();
                }
                break;

            case R.id.iv_ok_note:
                if (!Values.allurls.equals(""))
                    Values.allurls = Values.allurls.substring(0, Values.allurls.length() - 1);
                histroy.setContent(et_content.getText().toString().trim());
                histroy.setPlace(tv_place.getText().equals("地点：获取失败") ? "天津市大学生体育管" : tv_place.getText().toString());
                histroy.setTitle(TimeUtil.getdatestr());
                histroy.setUrl(Values.allurls);
                Values.allurls = "";
                FinalDb.create(Ac_Note.this, Values.DB_NAME).save(histroy);
                new CustomToast(Ac_Note.this).ShowMsg("保存成功！", CustomToast.Img_Ok);
                finish();
                break;
            case R.id.iv_addimg:
                if (checkSDCard()) {
                    Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    intent1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(photopath, "temp.jpg")));
                    startActivityForResult(intent1, 0);
                }
                break;
            case R.id.iv_fresh:
                RotateAnimation animation = new RotateAnimation(0, 1080, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setDuration(2000);
                iv_refresh.startAnimation(animation);
                tv_place.setText("正在获取...");
                getlocation();
                break;
            default:
                break;
        }
    }

    private boolean checkSDCard() {
        boolean b = true;
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) { // 判断是否存在SD卡
            String rootPath = Environment.getExternalStorageDirectory().getPath(); // 获取SD卡的根目录
            photopath = rootPath + Values.photo_Path;
            File file = new File(photopath);
            if (!file.exists()) {
                file.mkdirs();
            }
        } else {
            b = false;
            new AlertDialog.Builder(this)
                    .setMessage("检测到手机没有存储卡！请插入手机存储卡再开启本应用。")
                    .setNegativeButton("确定", null).show();
        }
        return b;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    File picture = new File(photopath, "temp.jpg");
                    System.out.println(picture.toString());
                    startPhotoZoom(Uri.fromFile(picture));
                    break;
                case 1:
                    Values.currenturl = photoname;
                    break;
                default:
                    break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 截切图片
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        photoname = System.currentTimeMillis() + ".jpg";
        File mypoto = new File(photopath, photoname);
        intent.putExtra("output", Uri.fromFile(mypoto));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);// 裁剪框比例
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputFormat", "JPEG");//返回格式
        intent.putExtra("outputX", 600);// 输出图片大小
        intent.putExtra("outputY", 400);
        intent.putExtra("return-data", false);//////////////[][][][重要]【新发现】
        startActivityForResult(intent, 1);
    }
}
